package permiss

import (
	"encoding/json"
	"fmt"
)
import "gotools/mssql"

type MenuPermission struct {
	MenuId             int64    `json:"MenuId"`
	MenuFunctionId     int64    `json:"MenuFunctionId"`
	DataPermissionType int      `json:"DataPermissionType"`
	DepartmentIds      []string `json:"DepartmentIds"`
}

func Getpermiss() {
	ms, err := mssql.NewMSSQLClient("192.168.18.77", "Super_User", "Super_User", "HuaDao.PermissionSystem")
	if err != nil {
		fmt.Println("Error creating MSSQL client:", err)
		return
	}
	defer ms.Close()

	// 执行查询
	rows, err := ms.Query("select top 1 b.Name appname,a.Name rolename,MenuIds,RoleMenuFunctions from role a JOIN Application b on a.ApplicationId=b.id where a.IsDeleted=0 and b.IsDeleted=0 and a.isopen=1")
	if err != nil {
		fmt.Println("Error executing query:", err)
		return
	}
	defer rows.Close()

	// 遍历查询结果
	for rows.Next() {
		var appname string
		var rolename string
		var MenuIds string
		var RoleMenuFunctions string
		if err := rows.Scan(&appname, &rolename, &MenuIds, &RoleMenuFunctions); err != nil {
			fmt.Println("Error scanning row:", err)
			return
		}
		//fmt.Println("appname:", appname, "rolename:", rolename, "MenuIds:", MenuIds, "RoleMenuFunctions:", RoleMenuFunctions)
		var permissions []MenuPermission
		err := json.Unmarshal([]byte(RoleMenuFunctions), &permissions)
		if err != nil {
			fmt.Println("Error:", err)
			return
		}

		for _, p := range permissions {
			fmt.Print("角色:", rolename)
			//fmt.Println("MenuId:", p.MenuId)
			//fmt.Println("MenuFunctionId:", p.MenuFunctionId)

			// var MenuFunctionId string
			querysql := fmt.Sprintf("select Name from menu WHERE id = %d", p.MenuId)
			rows, err = ms.Query(querysql)

			if err != nil {
				fmt.Println("Error executing query:", err)
				return
			}

			for rows.Next() {
				var menuname string
				if err := rows.Scan(&menuname); err != nil {
					fmt.Println("Error scanning row:", err)
				}
				fmt.Print("菜单:", menuname)
			}

			//查询menufunctionid
			querysql = fmt.Sprintf("select Name from MenuFunction WHERE id =  %d", p.MenuFunctionId)
			rows, err = ms.Query(querysql)

			if err != nil {
				fmt.Println("Error executing query:", err)
				return
			}

			for rows.Next() {
				var menufunctionname string
				if err := rows.Scan(&menufunctionname); err != nil {
					fmt.Println("Error scanning row:", err)
				}
				fmt.Print("menufunctionname:", menufunctionname)
			}
			fmt.Print("DataPermissionType:", p.DataPermissionType)
			fmt.Print("DepartmentIds:", p.DepartmentIds)
			fmt.Println()
		}
	}
}
